// import { APP_PUBLIC_KEY, APP_TOKEN } from '@/libs/constant';

const crypto = require('crypto-js');
const JSEncrypt = require('jsencrypt');

const getPublicKey = () => {
  const publicKey = sessionStorage.getItem('APP_PUBLIC_KEY') || localStorage.getItem('APP_PUBLIC_KEY') || localStorage.getItem('limitPublicKey') || localStorage.getItem('publicKey');
  console.log('publicKey-------')
  console.log(publicKey)
  if (!publicKey) {
    throw new Error(`The public key is [${publicKey}]`);
  }
  return publicKey;
};

const getToken = () => {
  const token = localStorage.getItem('APP_TOKEN') || localStorage.getItem('token');
  if (!token) {
    throw new Error(`The token is [${token}]`);
  }
  return token;
};

const AES_CONFIG = {
  iv: crypto.enc.Utf8.parse('chinavisionaryiv'),
  mode: crypto.mode.CBC,
  padding: crypto.pad.ZeroPadding,
};

/**
 * 加密
 *
 * @param data 加密前数据
 * @return {string} 加密后数据
 */
const encrypt = data => {
  let result = '';
  if (!data) {
    return result;
  }
  data = data instanceof Object ? JSON.stringify(data) : data.toString();
  const random = randomString(16);
  // 用AES加密明文数据
  const dataAfterAes = crypto.AES.encrypt(
    data,
    crypto.enc.Utf8.parse(random),
    AES_CONFIG,
  );
  return `${dataAfterAes}cvdata_separator${getRsaEncryptString(random)}`;
};

// RSA加密
const getRsaEncryptString = data => {
  const jencrypt = new JSEncrypt.JSEncrypt(); // 实例化加密对象
  jencrypt.setPublicKey(getPublicKey());
  return jencrypt.encrypt(data); // 加密明文
};

// 获取随机16位字符串
export const randomString = (length = 32) => {
  let text = '';
  const possible =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

export default encrypt;
export const AESDecrypt = encryptString => {
  if (!encryptString) {
    return '';
  }
  const data = crypto.AES.decrypt(
    encryptString,
    crypto.enc.Utf8.parse(getToken()),
    AES_CONFIG,
  );
  return data.toString(crypto.enc.Utf8);
};
